package com.example.demo.test;

import org.springframework.stereotype.Service;

import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Auther: csp
 * @Date: 2021/03/20/11:03
 * @Description:
 */
@Service
public class LimitService {

    //计数器
    private volatile AtomicInteger atomic = new AtomicInteger();

    private Semaphore semaphore = new Semaphore(10);


    public String visitCounter() throws Exception {
        //当前值超过10,表示qps已达到10
        if (atomic.get() > 10) {
            //拒绝请求
            return "throttle";
        }
        try {
            //没有达到10,计数器+1
            if (atomic.incrementAndGet() > 10) {
                return "throttle";
            }
            //处理请求
            Thread.sleep(1000);
            return "success";
        } finally {
            //释放资源
            atomic.decrementAndGet();
        }

    }

    public String visitSemaphore() throws Exception {
        //尝试获取资源池
        if (semaphore.tryAcquire()) {
            try {
                //处理请求
                //睡一秒展示效果
                Thread.sleep(1000);
                return "success";
            } finally {
                //释放资源
                semaphore.acquire();
            }
        } else {
            //资源池满了,拒绝请求直接返回
            return "throttle";
        }
    }
}
